package com.exina.android.calendar;

import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;


public class parserEvents
{
	// URL to fetch XML document with the events
	private URL documentUrl;
 
    public parserEvents() {
    }
 
    // Function to set the server url 
    public void setURL(String url) {
    	try {
			this.documentUrl = new URL(url);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
    }
    
    // Function to parse the event list
    public int[] parse() {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        int[] events = new int[7];
        
        //Array structure: -1 if no events are hold this day, event hour otherwise
        for (int i = 0; i < 7; i++)
        	events[i] = -1;
        
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document dom = builder.parse(this.getInputStream());
            Element root = dom.getDocumentElement();
            NodeList items = root.getElementsByTagName("semana");
            
            int aux = 0;
            
            for (int i=0; i<items.getLength(); i++) {
            	
                // XML Structure <semana><dia>x1</dia><hora>y1</hora><dia>x2</dia><hora>y2</hora>...</semana>
                Node item = items.item(i);
                NodeList items2 = item.getChildNodes();
                for (int j = 0; j < items2.getLength(); j++) {
                	Node item2 = items2.item(j);
                
	                String itemName = item2.getNodeName();
	                
	                if (itemName.equals("dia")) {
	                	//Get the day to override, 0 Sunday, 1 Monday...
	                	aux = Integer.parseInt(item2.getFirstChild().getNodeValue());
	                } 
	                else if (itemName.equals("hora")) {
	                	// Override the current day with given hour
	                	events[aux] = Integer.parseInt(item2.getFirstChild().getNodeValue());
	                }
                }
            }
        } 
        catch (Exception ex) {
            throw new RuntimeException(ex);
        }
        return events;
    }
 
    
    private InputStream getInputStream() {
        try {
            return documentUrl.openConnection().getInputStream();
        }
        catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}